package com.example.redisdelayqueue.common;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedissonDelayQueue {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 添加延迟队列
     *
     * @param value     队列值
     * @param delay     延迟时间
     * @param timeUnit  时间单位
     * @param queueCode 队列键
     * @param <T>
     */
    public <T> void pushDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode) {
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(value, delay, timeUnit);
            log.info("(添加延时队列成功) 队列键：{}，队列值：{}，延迟时间：{}秒", queueCode, value, timeUnit.toSeconds(delay));
        } catch (Exception e) {
            log.error("(添加延时队列失败) {}", e.getMessage());
            throw new RuntimeException("(添加延时队列失败)");
        }
    }

    /**
     * 获取延迟队列
     *
     * @param queueCode 队列键
     * @param <T>
     * @return
     * @throws InterruptedException
     */
    public <T> T popDelayQueue(String queueCode) throws InterruptedException {

        RBlockingQueue blockingDeque = redissonClient.getBlockingDeque(queueCode);
// 加了这个
        redissonClient.getDelayedQueue(blockingDeque);

//        RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        if(blockingDeque.isEmpty()) {
            return (T) Collections.emptyList();
        }
//        redissonClient.getDelayedQueue(blockingDeque);
        T value = (T) blockingDeque.take();
        return value;
    }

}
